#include <unordered_map>
#include "tcpsocket.hpp"
using namespace std;

std::unordered_map<string,string> table = {
  {"hello","nihao "},
  {"hi","hao" },
  {"chilma","youpomian"}
};
int main(int argc, char *argv[])
{
  if (argc < 2) {
    std::cout << "usage: ./tcp_srv 9000\n";
    return -1;

  }
  int port = std::stoi(argv[1]);
  TcpSocket lst_sock;
  //创建套接字
      CHECK_RET(lst_sock.Socket());
  //绑定地址信息, "0.0.0.0"会被识别为本机上任意网卡IP地址--绑定0.0.0.0就表示绑定了本机上所有网卡
  CHECK_RET(lst_sock.Bind("0.0.0.0", port));
  //开始监听
  CHECK_RET(lst_sock.Listen());
  while(1) {
    //获取新建连接,获取了与哪个客户端新建的连接，则与哪个客户端进行通信
    TcpSocket new_sock;
    std::string cli_ip;
    int cli_port;
    CHECK_RET(lst_sock.Accept(&new_sock, &cli_ip, &cli_port));
    std::cout << "new connect: " << cli_ip << ":" << cli_port << "\n";
    //使用新建连接收发数据, 一定要注意，通信使用的是新获取的套接字，而不是监听套接字
    std::string buf;
    new_sock.Recv(&buf);//接收数据
    struct cal_t *cal = (struct cal_t *)&buf[0];//获取空间首地址
    for (int i = 0; i < sizeof(struct cal_t); i++) {
      printf("%02x", buf[i]);
    }
    printf("\n");
    std::cout << cal->num1 << cal->op << cal->num2 << std::endl;
    int sum = 0;
    if (cal->op == '+') {
      sum = cal->num1 + cal->num2;
    }
    new_sock.Send(std::to_string(sum));//to_string将数字转string的接口
  }
  //关闭套接字
  lst_sock.Close();
  return 0;
}





